import React, { useState, useRef, useEffect, useMemo } from 'react';
import { Layout, Input, Button, List, Avatar, message, Row, Card, Col, Menu, Space, notification, } from 'antd';
import { CaretDownOutlined, CaretUpOutlined, ChromeOutlined } from '@ant-design/icons';
import { encrypt } from '@/utils/utils';
import TextArea from '../TextArea';
import { connect, history } from 'umi'
import dayjs from 'dayjs';
import {
    CopyOutlined,
    ReloadOutlined,
    LikeOutlined,
    DislikeOutlined
} from "@ant-design/icons";
import ReactMarkdown from 'react-markdown';
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import './index.less';

const { Header, Content, Footer } = Layout;
var eventSource = null
const handleCopy = (text) => {
    navigator.clipboard.writeText(text)
    notification.success({
        message: '温馨提示',
        description: '复制成功',
    });
};
const MessageActions = ({ onCopy, onRegenerate, onLike, onDislike, isRight, msg }) => {
    const { likeFlag } = msg
    return null
    // return (
    //     <div className={`actionBar ${isRight ? 'rightActions' : ''}`}>
    //         <CopyOutlined onClick={onCopy} title="复制" />
    //         {likeFlag === '0' || !likeFlag ? <>
    //             <LikeOutlined onClick={onLike} title="喜欢" />
    //             <DislikeOutlined onClick={onDislike} title="喜欢" />
    //         </> : likeFlag === '1' ? <LikeOutlined style={{ color: 'red' }} title="喜欢" /> : <DislikeOutlined style={{ color: 'red' }} title="不喜欢" />}

    //     </div>
    // );
};
const MarkdownComponents = {
    code({ node, inline, className, children, ...props }) {
        const match = /language-(\w+)/.exec(className || '');
        return !inline && match ? (
            <div style={{ border: '1px solid #333', borderRadius: '4px', margin: '16px 0' }}>
                {/* 头部栏 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    padding: '8px 12px',
                    background: '#1e1e1e',
                    borderBottom: '1px solid #333',
                    borderRadius: '4px 4px 0 0'
                }}>
                    {/* 语言标签 */}
                    <span style={{ color: '#888', fontSize: '0.875em' }}>
                        {match[1]}
                    </span>
                    {/* 复制按钮 */}
                    <button
                        onClick={() => {
                            handleCopy(String(children))
                        }}
                        style={{
                            background: 'transparent',
                            border: 'none',
                            color: '#888',
                            cursor: 'pointer',
                            fontSize: '0.875em',
                            display: 'flex',
                            alignItems: 'center',
                            gap: '4px'
                        }}
                    >
                        <>
                            <span>⎘</span>
                            <span>复制</span>
                        </>
                    </button>
                </div>
                <SyntaxHighlighter
                    style={vscDarkPlus}
                    customStyle={{
                        margin: '0px'
                    }}
                    language={match[1]}
                    showLineNumbers
                    PreTag="div"
                    {...props}
                >
                    {String(children).replace(/\n$/, '')}
                </SyntaxHighlighter>
            </div>

        ) : (
            <code className={className} {...props}>
                {children}
            </code>
        );
    },
};
function splitByThinkTag(str) {
    const tag = '</think>';
    const index = str.indexOf(tag);
    if (index === -1) return { before: str, after: '' };
    return {
        before: str.substring(0, index),
        after: str.substring(index + tag.length)
    };
}

const MessagesList = ({ messages, messageType, reload, dispatch }) => {
    const handleCopy = (text) => {
        navigator.clipboard.writeText(text)
        notification.success({
            message: '温馨提示',
            description: '复制成功',
        });
    };
    const LeftRender = (props) => {
        const { msg, } = props
        const [showSk, setshowSk] = useState(true)
        const { before, after } = splitByThinkTag(msg.allContent)
        const onLike = () => {
            dispatch({
                type: 'answering/fakeLikeChat',
                payload: {
                    id: msg.id,
                    likeFlag: '1'
                },
                callback: () => {
                    reload(messageType, {
                        ...msg,
                        likeFlag: '1'
                    })
                }
            })

        }
        const onDislike = () => {
            dispatch({
                type: 'answering/fakeLikeChat',
                payload: {
                    id: msg.id,
                    likeFlag: '0'
                },
                callback: () => {
                    reload(messageType, {
                        ...msg,
                        likeFlag: '0'
                    })
                }
            })
        }
        return <div
            key={msg.id}
            className={`messageBubble received`}
        >
            <div onClick={() => setshowSk(!showSk)} className='received_show_sk'>
                <Space>
                    <ChromeOutlined></ChromeOutlined> 已深度思考完成任务 {showSk ? <CaretDownOutlined ></CaretDownOutlined> : <CaretUpOutlined></CaretUpOutlined>}
                </Space>
            </div>
            {showSk && <div className='received_show_skContent'>
                <div className='received_show_skContentLiner'></div>
                <ReactMarkdown
                    components={MarkdownComponents}
                    remarkPlugins={[]}
                >
                    {before}
                </ReactMarkdown>
            </div>}
            <ReactMarkdown
                components={MarkdownComponents}
                remarkPlugins={[]}
            >
                {after}
            </ReactMarkdown>

            <MessageActions
                isRight={msg.isSent}
                onCopy={() => handleCopy(msg.allContent)}
                onLike={() => onLike()}
                onDislike={() => onDislike()}
                msg={msg}
            />

        </div>
    }
    const RightRender = (props) => {
        const { msg } = props
        return <div style={{ textAlign: 'right' }}>
            <div
                key={msg.id}
                className={`messageBubble sent`}
            >
                <div className={'messageContent'}>
                    {msg.allContent}
                </div>
            </div>
        </div>
    }
    const memo = useMemo(() => {
        return (
            <div className={'chatContainer'}>
                {messages.map((msg, index) => {
                    const { role } = msg
                    if (role === 'user') {
                        return <RightRender key={index} msg={msg}></RightRender>
                    } else {
                        return <LeftRender key={index} msg={msg}></LeftRender>
                    }
                })}
            </div>
        );
    }, [messages])
    return memo
};
const Messages = ({ msg, messageType, reload, dispatch, status }) => {
    const [showSk, setshowSk] = useState(true)
    const { before, after } = splitByThinkTag(msg.allContent)
    const onLike = () => {
        dispatch({
            type: 'answering/fakeLikeChat',
            payload: {
                id: msg.id,
                likeFlag: '1'
            },
            callback: () => {
                reload(messageType, {
                    ...msg,
                    likeFlag: '1'
                })
            }
        })

    }
    const onDislike = () => {
        dispatch({
            type: 'answering/fakeLikeChat',
            payload: {
                id: msg.id,
                likeFlag: '0'
            },
            callback: () => {
                reload(messageType, {
                    ...msg,
                    likeFlag: '0'
                })
            }
        })
    }
    const handleCopy = (text) => {
        navigator.clipboard.writeText(text)
        notification.success({
            message: '温馨提示',
            description: '复制成功',
        });
    };

    return (
        <div className={'chatContainer'}>
            <div
                key={msg.id}
                className={`messageBubble received`}
            >
                <div onClick={() => setshowSk(!showSk)} className='received_show_sk'>
                    <Space>
                        <ChromeOutlined></ChromeOutlined>{status ? '正在思考请耐心等待' : '已深度思考完成任务'}  {showSk ? <CaretDownOutlined ></CaretDownOutlined> : <CaretUpOutlined></CaretUpOutlined>}
                    </Space>
                </div>
                {showSk && <div className='received_show_skContent'>
                    <div className='received_show_skContentLiner'></div>
                    <ReactMarkdown
                        components={MarkdownComponents}
                        remarkPlugins={[]}
                    >
                        {before}
                    </ReactMarkdown>
                </div>}
                <ReactMarkdown
                    components={MarkdownComponents}
                    remarkPlugins={[]}
                >
                    {after}
                </ReactMarkdown>

                <MessageActions
                    isRight={msg.isSent}
                    onCopy={() => handleCopy(msg.allContent)}
                    onLike={() => onLike()}
                    onDislike={() => onDislike()}
                    msg={msg}
                />

            </div>
        </div>
    );
};
const ChatApp = (props) => {
    const { dispatch, loading, data = {} } = props
    const { title, id } = data
    const { location = {} } = history
    const [messages, setMessages] = useState([]);
    const [streamData, setStreamData] = useState('');
    const [value, setValue] = useState('')
    const [status, setStatus] = useState(false);
    const [chatId, setChatId] = useState('')
    const [error, setError] = useState(null);
    const dataBuffer = useRef(''); // 数据缓冲区
    const messagesEndRef = useRef(null);
    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({});
    };
    const fetchData = () => {
        dispatch({
            type: 'answering/fetchAnalysisListTitleChat',
            payload: {
                titleId: id
            },
            callback: (e) => {
                setMessages(e)
            }

        })
    }
    const submit = () => {
        if (eventSource) {
            eventSource.close()
            eventSource = null
        }
        setStreamData('')
        fetchData()
        postAndStream(value)
        setValue('')
    }
    async function postAndStream(prompt) {
        if (!prompt || prompt.replace(/[\r\n ]/g, '').length === 0) {
            return notification.warning({
                message: '温馨提示',
                description: '请输入问题后提交',
            })
        }
        if (status) {
            return
        }
        if (eventSource) {
            eventSource.close()
        }
        const payload = {
            titleId: id,
            prompt: encodeURIComponent(prompt.replace(/[\r\n]/g, '')),
            token: window.localStorage.getItem('token'),
            device: 'web'
        }
        const signPayload = encrypt({
            titleId: id,
            prompt: prompt.replace(/[\r\n]/g, ''),
            token: window.localStorage.getItem('token'),
            device: 'web'
        })
        const newPayload = { ...signPayload, ...payload }

        const str = Object.keys(newPayload)
            .map((item) => {
                return `${item}=${newPayload[item]}`;
            })
            .join("&");
        console.log(APIURL + `/gpt/adminChat?${str}`)
        eventSource = new EventSource(APIURL + `/gpt/adminChat?${str}`);
        eventSource.onopen = (event) => {
            setStatus(true)
        }
        // 2. 处理消息事件
        eventSource.onmessage = (event) => {
            try {
                const parsedData = JSON.parse(event.data);
                const { content, finishReason, aiChatId } = parsedData
                if (finishReason === 'stop') {
                    setStatus(false)
                    eventSource.close()
                    eventSource = null
                    setChatId(aiChatId)
                    return
                }

                setStreamData((e) => {
                    return e + content
                })
            } catch (e) {
                console.error('解析数据失败:', e);
            }
        };

        // 3. 处理错误事件
        eventSource.onerror = (error) => {
            debugger;
            setError('连接出错，尝试重新连接...');
            setStatus(false)
            console.error('EventSource错误:', error);
            // 可根据需要关闭连接，但EventSource默认会自动重连
            // eventSource.close();
        };
    }
    useEffect(() => {
        if (id) {
            fetchData()
        }
    }, [id])
    useEffect(() => {
        scrollToBottom();
    }, [messages, streamData]);

    const reload = (messageType, data) => {
        if (messageType === 'bottom') {
            setStreamData('')
            setChatId('')
            fetchData()
        }
        else {
            messages.map((item) => {
                const { id } = item
                if (id == data.id) {
                    return {
                        ...item,
                        ...data
                    }
                }
                return item
            })
        }
    }

    return (
        <Layout className="chat-container">
            <Header className="chat-header">
                <div className="header-content">
                    <h2 className="header-title font_hide">{title}</h2>
                </div>
            </Header>

            <Content className="chat-content">
                <MessagesList dispatch={dispatch} messageType={'list'} reload={reload} messages={messages}></MessagesList>
                {/* {(streamData.length || status) && <Messages status={status} messageType={'bottom'} reload={reload} dispatch={dispatch} msg={
                    {
                        role: "assistant",
                        allContent: streamData,
                        title: prompt,
                        id: chatId
                    }
                }></Messages>} */}
                <div ref={messagesEndRef} />
            </Content>
            {/* 
            <Footer className="chat-footer">
                <div style={{ margin: '0 auto' }} className='AnsweringAis_left_btn'>
                    <div onClick={() => {
                        notification.warning({
                            message: '温馨提示',
                            description: '暂不支持',
                        });
                    }} className='AnsweringAis_left_btnStyle'>
                        <div className='AnsweringAis_left_btn1'>
                            <div className='AnsweringAis_icon_style'>
                                <ChromeOutlined></ChromeOutlined>
                            </div>

                            开启新对话
                        </div>
                    </div>
                </div>
                <TextArea
                    loading={status}
                    onOk={submit}
                    value={value}
                    onChange={(e) => {
                        setValue(e.target.value)
                    }}>

                </TextArea>
            </Footer> */}
        </Layout>
    );
};

export default connect(({ loading, answering }) => ({
    list: answering.dateAiChatTitleList,
    loading: loading.models.answering,
}))(ChatApp);

